package cn.boge.hrm.service.impl;

import cn.boge.hrm.doc.CourseDoc;
import cn.boge.hrm.dto.CourseSearchParamDTO;
import cn.boge.hrm.mapper.HighlightResultMapper;
import cn.boge.hrm.repository.CourseESRepository;
import cn.boge.hrm.service.ICourseES;
import cn.boge.hrm.util.PageList;
import cn.boge.hrm.vo.AggPageListVo;
import cn.boge.hrm.vo.Bucket;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseESImpl implements ICourseES {
    @Autowired
    private CourseESRepository courseESRepository;
    @Autowired
    private ElasticsearchRestTemplate template;
    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public void save(CourseDoc couresDoc) {
        courseESRepository.save(couresDoc);
    }

    @Override
    public PageList<CourseDoc> searchCourse(CourseSearchParamDTO dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //分页
        builder.withPageable(PageRequest.of(dto.getPage() - 1, dto.getRows()));
        //排序
        if (StringUtils.isNotEmpty(dto.getSortField())) {
            String sortF = "onlieTime";
            switch (dto.getSortField()) {
                case "xl":
                    sortF = "saleCount";
                    break;
                case "xp":
                    sortF = "onlieTime";
                    break;
                case "jg":
                    sortF = "price";
                    break;
                case "rq":
                    sortF = "viewCount";
                    break;
                case "pl":
                    sortF = "commentCount";
                    break;
            }
            SortOrder sortOrder = SortOrder.DESC;
            if (StringUtils.isNotEmpty(dto.getSortType()) && dto.getSortType().equalsIgnoreCase("asc"))
                sortOrder = SortOrder.ASC;
            builder.withSort(new FieldSortBuilder(sortF).order(sortOrder));
        }
        //查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //dsl查询
        if (StringUtils.isNotEmpty(dto.getKeyword()))
            //boolQueryBuilder.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
            boolQueryBuilder.must(QueryBuilders.matchQuery("searchField", dto.getKeyword()));
        //dsl过滤
        dto.getGradeName();
        dto.getPriceMax();
        dto.getPriceMin();
        if (null != dto.getCourseTypeId())
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId", dto.getCourseTypeId()));
        if (StringUtils.isNotEmpty(dto.getGradeName()))
            boolQueryBuilder.filter(QueryBuilders.termQuery("gradeName", dto.getGradeName()));
        if (null != dto.getPriceMax())
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        if (null != dto.getPriceMin())
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));

        builder.withQuery(boolQueryBuilder);
        //处理高亮
        HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                .preTags("<font style='color:red;font-size:17px'>")
                .postTags("</font>");
        builder.withHighlightFields(field);
        //聚合
        //等级聚合
        TermsAggregationBuilder geadeAgg = AggregationBuilders.terms("gradeAgg").field("gradeName");
        //机构聚合
        TermsAggregationBuilder tenantAgg = AggregationBuilders.terms("tenantAgg").field("tenantName");
        //builder.addAggregation(geadeAgg).addAggregation(tenantAgg);
        ////创建查询
        //SearchQuery searchQuery = builder.build();
        ////查询执行
        ////Page<CourseDoc> page = courseESRepository.search(searchQuery);
        //AggregatedPage<CourseDoc> page = template.queryForPage(searchQuery, CourseDoc.class, highlightResultMapper);
        //Aggregations aggregations = page.getAggregations();
        //Map<String, Aggregation> aggregationMap = aggregations.asMap();
        //System.out.println("============每一个=============");
        //aggregationMap.entrySet().forEach(entry -> {
        //    //聚合名字
        //    String aggname = entry.getKey();
        //    System.out.println("聚合的名字：" + aggname);
        //    //聚合对象
        //    ParsedStringTerms aggregation = (ParsedStringTerms) entry.getValue();
        //    List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
        //    buckets.forEach(bucket -> {
        //        String key = bucket.getKeyAsString();
        //        long docCount = bucket.getDocCount();
        //        System.out.println("bucket的key=" + key + "docCount=" + docCount);
        //    });
        //});
        ////封装一个dto把查出来的数据存进去就行
        //
        //return new PageList<>(page.getTotalElements(), page.getContent());
        builder.addAggregation(geadeAgg).addAggregation(tenantAgg);
        //创建查询对象
        SearchQuery searchQuery = builder.build();
        //执行搜索
        /* Page<CourseDoc> page = repository.search(searchQuery);*/
        AggregatedPage<CourseDoc> page = template.queryForPage(searchQuery, CourseDoc.class, highlightResultMapper);
        //从返回值结果里面获取聚合数据
        Aggregations aggregations = page.getAggregations();
        //System.out.println(aggregations);
        //聚合名就是key
        Map<String, Aggregation> aggregationMap = aggregations.asMap();
        Map<String , List<Bucket> > agg = new HashMap<>();
        aggregationMap.entrySet().forEach(entry ->{
            String aggNamme = entry.getKey();
            ParsedStringTerms aggregation = (ParsedStringTerms) entry.getValue();
            //再从value里面获取baket
            List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
            //再进行循环取值
            List<Bucket> buckets1 = new ArrayList<>();
            buckets.forEach(bucket -> {
                String key = (String) bucket.getKey();
                long docCount = bucket.getDocCount();
                buckets1.add(new Bucket(key,docCount));
            });
            agg.put(aggNamme,buckets1);

        });
        //获取搜素得到的总条数
        long totals = page.getTotalElements();
        //获取搜素得到的数据
        List<CourseDoc> courseDocs = page.getContent();
        return new AggPageListVo(totals,courseDocs,agg);
    }
}
